
<template>
  <div class="search_page">
    <!-- 搜索区 -->
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入你要搜索的商品"
        @search="onSearch"
        @input="onInput"
        @cancel="onCancel"
      />
    </form>
    <!-- <div class="search_wrap">
      <input type="text" placeholder="请输入你要搜索的商品" @input="handleInput" :value="inputValue" />
      <button :hidden="!isFocus" @click="cancelBtn">取消</button>
    </div>-->
    <!-- 结果 -->
    <div class="search_content">
      <div
        class="search_item"
        v-for="(item,index) in resultGoods"
        :key="index"
        @click="toGoodsDetail(item.goods_id)"
      >{{item.goods_name}}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      resultGoods: [],
      isFocus: false,
      value: '',
      inputValue: ''
    }
  },
  TimeId: -1,
  methods: {
    onSearch(val) {
      console.log(val)
    },
    onInput(val) {
      clearTimeout(this.TimeId)
      this.TimeId = setTimeout(val => {
        this.qsearch(1)
      }, 1000)
    },
    onCancel() {
      this.$toast('取消')
    },
    // 输入东西
    handleInput(e) {
      console.log(e)
      const { value } = e.target
      if (!value.trim()) {
        this.resultGoods = []
        this.isFocus = false
        return
      }
      this.isFocus = true
      // 定时器
      clearTimeout(this.TimeId)
      this.TimeId = setTimeout(() => {
        this.qsearch(value)
      }, 1000)
    },
    cancelBtn() {
      this.resultGoods = []
      this.inputValue = ''
    },
    // 搜索请求
    async qsearch(query) {
      console.log('query', query)
      const res = await this.$http.get('goods/qsearch', {
        params: { query: query }
      })
      console.log(res)
      this.resultGoods = res.data.message
    },
    toGoodsDetail(goods_id) {
      this.$router.push({ name: 'GoodsDetail', params: { goods_id: goods_id } })
    }
  }
}
</script>
<style lang='less' scoped>
.search_page {
  padding: 10px;
  // height: calc(~'100hv - 50px');
  background-color: #eee;
}

.search_wrap {
  width: 100%;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;

  input {
    flex: 1;
    height: 100%;
    background-color: #ffffff;
    padding-left: 15px;
  }

  button {
    width: 55px;
    height: 100%;
    font-size: 13px;
    padding: 0;
    margin-left: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.search_content {
  background-color: #fff;
  margin-top: 15px;

  .search_item {
    border: 1px solid #ccc;
    font-size: 13px;
    padding: 15px 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
